<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <!-- 未登录状态 -->
      <a-link v-if="!store.state.user.loginUser.id" @click="gologin">
        未登录</a-link
      >
      <!-- 已登录状态 -->
      <a-popover v-else trigger="click" position="bottom">
        <!-- 没名称用户 -->
        <a-avatar>
          <img
            alt="avatar"
            :src="
              store.state.user.loginUser.userAvatar ??
              'https://img.ixintu.com/download/jpg/20200910/f9256155491e54bf5e99bf29eece0156_512_512.jpg!ys'
            "
          />
        </a-avatar>
        <template #content>
          <div class="user-popover-content">
            <p class="user-menu-item" @click="goToUserProfile">
              <icon-user style="margin-right: 8px" />个人信息
            </p>
            <p class="user-menu-item logout" @click="logout">
              <icon-export style="margin-right: 8px" />退出登录
            </p>
          </div>
        </template>
      </a-popover>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "../router/routes";
import { useRouter } from "vue-router";
import { computed, ref, onMounted } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";
import { IconUser, IconExport } from "@arco-design/web-vue/es/icon";

const router = useRouter();
const store = useStore();

// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});

// 默认主页
const selectedKeys = ref(["/home"]);

// 路由跳转后，更新选中的菜单项
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});

// 组件挂载时获取用户信息
onMounted(() => {
  store.dispatch("user/getLoginUser");
});

const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};

const logout = async () => {
  try {
    // 调用后端退出接口
    await fetch("/api/logout", {
      method: "POST",
      credentials: "include", // 确保携带 Cookie
    });

    // 清除前端状态
    await store.dispatch("user/logout");
    localStorage.removeItem("user");
    localStorage.removeItem("loginUser");
    // 跳转到登录页面
    router.push({ path: "/user/login" });
  } catch (error) {
    console.error("退出失败", error);
  }
};

const gologin = () => {
  router.push({
    path: "/user/login",
  });
};

// 转到用户个人信息页面
const goToUserProfile = () => {
  router.push({
    path: "/user/profile",
  });
};
</script>

<style scoped>
.logout {
  cursor: pointer;
}

.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
}

.logo {
  height: 48px;
}

.user-popover-content {
  min-width: 120px;
  text-align: center;
}

.user-menu-item {
  padding: 8px 0;
  margin: 8px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.3s;
}

.user-menu-item:hover {
  color: #165dff;
}
</style>
